"""
Content Creation View for Desktop Application
桌面应用内容创建界面
"""

import logging
from typing import Optional, Dict, Any, List
import asyncio

import flet as ft
from flet import (
    Page,
    Container,
    Column,
    Row,
    Text,
    TextField,
    ElevatedButton,
    IconButton,
    Dropdown,
    dropdown,
    Icon,
    Icons,
    Colors,
    Card,
    Divider,
    ExpansionPanel,
    ExpansionPanelList,
    Slider,
    Checkbox,
    Radio,
    RadioGroup,
    Image,
    ProgressRing,
    Badge,
    AlertDialog,
    FilePicker,
    FilePickerResultEvent,
    Tabs,
    Tab,
)

from ..services.api_client import APIClient
from ..core.state_manager import StateManager

logger = logging.getLogger(__name__)


class ContentCreationView:
    """内容创建界面视图类"""
    
    def __init__(self, page: Page, state_manager: StateManager, api_client: APIClient):
        self.page = page
        self.state_manager = state_manager
        self.api_client = api_client
        
        # 界面组件
        self.content: Optional[Container] = None
        self.main_column: Optional[Column] = None
        
        # 基础设置组件
        self.prompt_textfield: Optional[TextField] = None
        self.content_type_dropdown: Optional[Dropdown] = None
        self.ai_provider_dropdown: Optional[Dropdown] = None
        self.ai_model_dropdown: Optional[Dropdown] = None
        self.generate_button: Optional[ElevatedButton] = None
        
        # 高级设置组件
        self.negative_prompt_textfield: Optional[TextField] = None
        self.width_slider: Optional[Slider] = None
        self.height_slider: Optional[Slider] = None
        self.quality_dropdown: Optional[Dropdown] = None
        self.style_dropdown: Optional[Dropdown] = None
        self.count_slider: Optional[Slider] = None
        self.advanced_expansion_panel: Optional[ExpansionPanelList] = None
        
        # 状态
        self.is_generating: bool = False
        self.generation_tasks: List[Dict[str, Any]] = []
        self.current_provider: str = "doubao"
        self.current_content_type: str = "image"
        
        # 文件选择器
        self.file_picker: Optional[FilePicker] = None
        
    async def show(self) -> None:
        """显示内容创建界面"""
        try:
            logger.info("Showing content creation view")
            
            # 创建界面组件
            await self._create_interface()
            
            # 初始化文件选择器
            await self._initialize_file_picker()
            
            # 加载默认设置
            await self._load_default_settings()
            
            logger.info("Content creation view shown successfully")
            
        except Exception as e:
            logger.error(f"Failed to show content creation view: {e}")
            raise
    
    def get_content(self) -> Container:
        """获取界面内容"""
        return self.content
    
    async def _create_interface(self) -> None:
        """创建界面"""
        # 创建基础设置区域
        basic_settings = self._create_basic_settings()
        
        # 创建高级设置区域
        advanced_settings = self._create_advanced_settings()
        
        # 创建生成任务区域
        generation_tasks = self._create_generation_tasks_area()
        
        # 创建主列
        self.main_column = Column([
            # 标题区域
            Container(
                content=Column([
                    Text("内容创建", size=28, weight=ft.FontWeight.BOLD),
                    Text(
                        "使用AI技术创建图像、视频、音频等多媒体内容",
                        size=16,
                        color=colors.SECONDARY,
                    ),
                ], spacing=5),
                padding=ft.padding.only(bottom=20),
            ),
            
            # 基础设置卡片
            Card(
                content=Container(
                    content=basic_settings,
                    padding=20,
                ),
                elevation=2,
            ),
            
            # 高级设置卡片
            Card(
                content=Container(
                    content=advanced_settings,
                    padding=20,
                ),
                elevation=2,
            ),
            
            # 生成按钮区域
            Container(
                content=self.generate_button,
                padding=ft.padding.symmetric(vertical=20),
                alignment=ft.alignment.center,
            ),
            
            # 生成任务区域
            generation_tasks,
        ],
        spacing=20,
        scroll=ft.ScrollMode.AUTO,
        )
        
        # 创建主内容容器
        self.content = Container(
            content=self.main_column,
            padding=20,
            expand=True,
        )
    
    def _create_basic_settings(self) -> Column:
        """创建基础设置"""
        # 内容类型选择
        self.content_type_dropdown = Dropdown(
            label="内容类型",
            hint_text="选择要生成的内容类型",
            options=[
                dropdown.Option("image", "图像"),
                dropdown.Option("video", "视频"),
                dropdown.Option("audio", "音频"),
                dropdown.Option("text", "文本"),
            ],
            value="image",
            on_change=self._on_content_type_change,
        )
        
        # AI提供商选择
        self.ai_provider_dropdown = Dropdown(
            label="AI模型提供商",
            hint_text="选择AI模型提供商",
            options=[
                dropdown.Option("doubao", "豆包大模型 (推荐)"),
                dropdown.Option("ali", "阿里云大模型"),
                dropdown.Option("openai", "OpenAI"),
            ],
            value="doubao",
            on_change=self._on_ai_provider_change,
        )
        
        # AI模型选择
        self.ai_model_dropdown = Dropdown(
            label="AI模型",
            hint_text="选择具体的AI模型",
            options=self._get_model_options("doubao", "image"),
            value=self._get_default_model("doubao", "image"),
        )
        
        # 提示词输入
        self.prompt_textfield = TextField(
            label="提示词",
            hint_text="描述您想要生成的内容...",
            multiline=True,
            min_lines=3,
            max_lines=6,
            expand=True,
        )
        
        # 生成按钮
        self.generate_button = ElevatedButton(
            text="生成内容",
            icon=icons.PLAY_CIRCLE,
            style=ft.ButtonStyle(
                bgcolor=colors.PRIMARY,
                color=colors.ON_PRIMARY,
                padding=ft.padding.symmetric(horizontal=30, vertical=15),
                elevation=5,
            ),
            width=200,
            height=50,
            on_click=self._on_generate_click,
        )
        
        return Column([
            Row([
                self.content_type_dropdown,
                self.ai_provider_dropdown,
                self.ai_model_dropdown,
            ], spacing=20),
            self.prompt_textfield,
        ], spacing=20)
    
    def _create_advanced_settings(self) -> Column:
        """创建高级设置"""
        # 负面提示词
        self.negative_prompt_textfield = TextField(
            label="负面提示词（可选）",
            hint_text="描述您不希望在生成内容中出现的内容...",
            multiline=True,
            min_lines=2,
            max_lines=4,
        )
        
        # 尺寸设置
        self.width_slider = Slider(
            label="宽度: {value}px",
            min=64,
            max=2048,
            divisions=30,
            value=1024,
        )
        
        self.height_slider = Slider(
            label="高度: {value}px",
            min=64,
            max=2048,
            divisions=30,
            value=1024,
        )
        
        # 质量设置
        self.quality_dropdown = Dropdown(
            label="生成质量",
            options=[
                dropdown.Option("low", "低质量（快速）"),
                dropdown.Option("medium", "中等质量"),
                dropdown.Option("high", "高质量"),
                dropdown.Option("ultra", "超高质量（慢速）"),
            ],
            value="high",
        )
        
        # 风格设置
        self.style_dropdown = Dropdown(
            label="艺术风格",
            options=[
                dropdown.Option("realistic", "写实风格"),
                dropdown.Option("cartoon", "卡通风格"),
                dropdown.Option("anime", "动漫风格"),
                dropdown.Option("abstract", "抽象风格"),
                dropdown.Option("oil_painting", "油画风格"),
                dropdown.Option("watercolor", "水彩风格"),
                dropdown.Option("sketch", "素描风格"),
            ],
            value="realistic",
        )
        
        # 生成数量
        self.count_slider = Slider(
            label="生成数量: {value}",
            min=1,
            max=10,
            divisions=9,
            value=1,
        )
        
        # 创建展开面板
        expansion_panel = ExpansionPanel(
            header=Text("高级设置", size=16, weight=ft.FontWeight.BOLD),
            content=Column([
                self.negative_prompt_textfield,
                Row([
                    Column([
                        Text("图像尺寸", size=14, weight=ft.FontWeight.BOLD),
                        self.width_slider,
                        self.height_slider,
                    ], expand=True),
                    Column([
                        self.quality_dropdown,
                        self.style_dropdown,
                    ], expand=True),
                ], spacing=20),
                Row([
                    Text("生成数量", size=14, weight=ft.FontWeight.BOLD),
                    self.count_slider,
                ], spacing=10),
            ], spacing=15),
            expanded=False,
        )
        
        self.advanced_expansion_panel = ExpansionPanelList([expansion_panel])
        
        return Column([
            Text("高级设置", size=18, weight=ft.FontWeight.BOLD),
            self.advanced_expansion_panel,
        ], spacing=10)
    
    def _create_generation_tasks_area(self) -> Container:
        """创建生成任务区域"""
        return Container(
            content=Column([
                Row([
                    Text("生成任务", size=18, weight=ft.FontWeight.BOLD),
                    Badge(
                        content=Text(str(len(self.generation_tasks))),
                        visible=len(self.generation_tasks) > 0,
                    ),
                ], spacing=10),
                Text(
                    "暂无进行中的生成任务",
                    size=14,
                    color=colors.SECONDARY,
                    visible=len(self.generation_tasks) == 0,
                ),
            ], spacing=10),
            padding=20,
            bgcolor=colors.SURFACE_VARIANT,
            border_radius=8,
            visible=True,
        )
    
    def _get_model_options(self, provider: str, content_type: str) -> List[dropdown.Option]:
        """获取模型选项"""
        model_configs = {
            "doubao": {
                "image": [
                    ("doubao-image-v1", "豆包图像生成V1"),
                    ("doubao-image-v2", "豆包图像生成V2"),
                ],
                "video": [
                    ("doubao-video-v1", "豆包视频生成V1"),
                ],
                "audio": [
                    ("doubao-audio-v1", "豆包音频生成V1"),
                ],
                "text": [
                    ("doubao-text-v1", "豆包文本生成V1"),
                ],
            },
            "ali": {
                "image": [
                    ("ali-image-v1", "阿里云图像生成V1"),
                    ("ali-image-v2", "阿里云图像生成V2"),
                ],
                "video": [
                    ("ali-video-v1", "阿里云视频生成V1"),
                ],
                "audio": [
                    ("ali-audio-v1", "阿里云音频生成V1"),
                ],
                "text": [
                    ("ali-text-v1", "阿里云文本生成V1"),
                ],
            },
            "openai": {
                "image": [
                    ("dall-e-3", "DALL-E 3"),
                    ("dall-e-2", "DALL-E 2"),
                ],
                "text": [
                    ("gpt-4", "GPT-4"),
                    ("gpt-3.5-turbo", "GPT-3.5 Turbo"),
                ],
            },
        }
        
        models = model_configs.get(provider, {}).get(content_type, [])
        return [dropdown.Option(value, label) for value, label in models]
    
    def _get_default_model(self, provider: str, content_type: str) -> str:
        """获取默认模型"""
        defaults = {
            "doubao": {
                "image": "doubao-image-v1",
                "video": "doubao-video-v1",
                "audio": "doubao-audio-v1",
                "text": "doubao-text-v1",
            },
            "ali": {
                "image": "ali-image-v1",
                "video": "ali-video-v1",
                "audio": "ali-audio-v1",
                "text": "ali-text-v1",
            },
            "openai": {
                "image": "dall-e-3",
                "text": "gpt-4",
            },
        }
        
        return defaults.get(provider, {}).get(content_type, "")
    
    async def _initialize_file_picker(self) -> None:
        """初始化文件选择器"""
        self.file_picker = FilePicker(on_result=self._on_file_picked)
        self.page.overlay.append(self.file_picker)
    
    async def _load_default_settings(self) -> None:
        """加载默认设置"""
        try:
            # 从状态管理器加载用户偏好设置
            default_provider = await self.state_manager.get_setting("default_ai_provider", "doubao")
            if self.ai_provider_dropdown:
                self.ai_provider_dropdown.value = default_provider
                self.current_provider = default_provider
            
            # 更新模型选项
            await self._update_model_options()
            
        except Exception as e:
            logger.error(f"Failed to load default settings: {e}")
    
    # 事件处理
    async def _on_content_type_change(self, e) -> None:
        """内容类型变更"""
        self.current_content_type = e.control.value
        await self._update_model_options()
        await self._update_advanced_settings()
    
    async def _on_ai_provider_change(self, e) -> None:
        """AI提供商变更"""
        self.current_provider = e.control.value
        await self._update_model_options()
        await self._update_advanced_settings()
    
    async def _on_generate_click(self, e) -> None:
        """生成按钮点击"""
        await self._perform_content_generation()
    
    async def _on_file_picked(self, e: FilePickerResultEvent) -> None:
        """文件选择回调"""
        if e.files:
            # 处理选择的文件
            for file in e.files:
                logger.info(f"Selected file: {file.name} - {file.path}")
            
            self.page.show_snack_bar(
                ft.SnackBar(
                    content=Text(f"已选择 {len(e.files)} 个文件"),
                    duration=2000,
                )
            )
    
    # 业务逻辑
    async def _update_model_options(self) -> None:
        """更新模型选项"""
        try:
            if self.ai_model_dropdown:
                # 获取新的模型选项
                new_options = self._get_model_options(self.current_provider, self.current_content_type)
                
                # 更新选项
                self.ai_model_dropdown.options = new_options
                
                # 设置默认值
                if new_options:
                    self.ai_model_dropdown.value = new_options[0].key
                else:
                    self.ai_model_dropdown.value = None
                
                self.page.update()
                
        except Exception as e:
            logger.error(f"Failed to update model options: {e}")
    
    async def _update_advanced_settings(self) -> None:
        """更新高级设置"""
        try:
            # 根据提供商和内容类型更新可用的高级选项
            if self.advanced_expansion_panel:
                # 这里可以根据不同的提供商和内容类型动态调整高级设置
                pass
                
        except Exception as e:
            logger.error(f"Failed to update advanced settings: {e}")
    
    async def _perform_content_generation(self) -> None:
        """执行内容生成"""
        if self.is_generating:
            return
        
        try:
            # 获取表单数据
            prompt = self.prompt_textfield.value
            content_type = self.content_type_dropdown.value
            ai_provider = self.ai_provider_dropdown.value
            ai_model = self.ai_model_dropdown.value
            
            # 验证输入
            if not prompt or not prompt.strip():
                self._show_error("请输入提示词")
                return
            
            if not content_type:
                self._show_error("请选择内容类型")
                return
            
            if not ai_provider:
                self._show_error("请选择AI模型提供商")
                return
            
            if not ai_model:
                self._show_error("请选择AI模型")
                return
            
            # 获取高级设置
            parameters = self._get_advanced_parameters()
            
            # 设置生成状态
            self._set_generating_state(True)
            
            # 调用API生成内容
            logger.info(f"Starting content generation: {content_type} with {ai_provider}")
            
            response = await self.api_client.create_content(
                prompt=prompt,
                content_type=content_type,
                ai_provider=ai_provider,
                parameters=parameters
            )
            
            if response.get("success"):
                # 生成成功
                task_data = response.get("data", {})
                
                # 添加到任务列表
                await self._add_generation_task(task_data)
                
                # 显示成功消息
                self._show_success("内容生成任务已提交成功！")
                
                # 清空提示词
                if self.prompt_textfield:
                    self.prompt_textfield.value = ""
                
                # 更新状态管理器
                await self.state_manager.add_generation_task(task_data)
                
                logger.info(f"Content generation task created: {task_data.get('request_id')}")
                
            else:
                # 生成失败
                error_message = response.get("error", {}).get("message", "生成失败")
                self._show_error(f"生成失败: {error_message}")
                
        except Exception as e:
            logger.error(f"Content generation error: {e}")
            self._show_error(f"生成失败: {str(e)}")
            
        finally:
            self._set_generating_state(False)
    
    def _get_advanced_parameters(self) -> Dict[str, Any]:
        """获取高级参数"""
        parameters = {}
        
        # 负面提示词
        if self.negative_prompt_textfield and self.negative_prompt_textfield.value:
            parameters["negative_prompt"] = self.negative_prompt_textfield.value
        
        # 尺寸设置
        if self.width_slider:
            parameters["width"] = int(self.width_slider.value)
        
        if self.height_slider:
            parameters["height"] = int(self.height_slider.value)
        
        # 质量设置
        if self.quality_dropdown:
            parameters["quality"] = self.quality_dropdown.value
        
        # 风格设置
        if self.style_dropdown:
            parameters["style"] = self.style_dropdown.value
        
        # 生成数量
        if self.count_slider:
            parameters["count"] = int(self.count_slider.value)
        
        # AI模型
        if self.ai_model_dropdown:
            parameters["ai_model"] = self.ai_model_dropdown.value
        
        return parameters
    
    async def _add_generation_task(self, task_data: Dict[str, Any]) -> None:
        """添加生成任务"""
        self.generation_tasks.append(task_data)
        await self._update_generation_tasks_display()
    
    async def _update_generation_tasks_display(self) -> None:
        """更新生成任务显示"""
        # TODO: 实现任务列表显示
        pass
    
    # UI辅助方法
    def _set_generating_state(self, is_generating: bool) -> None:
        """设置生成状态"""
        self.is_generating = is_generating
        
        # 更新生成按钮
        if self.generate_button:
            self.generate_button.disabled = is_generating
            
            if is_generating:
                self.generate_button.content = Row([
                    ProgressRing(width=16, height=16, stroke_width=2),
                    Text("生成中..."),
                ], spacing=10)
                self.generate_button.style = ft.ButtonStyle(
                    bgcolor=colors.ORANGE,
                    color=colors.ON_ORANGE,
                )
            else:
                self.generate_button.content = Row([
                    Icon(icons.PLAY_CIRCLE),
                    Text("生成内容"),
                ], spacing=10)
                self.generate_button.style = ft.ButtonStyle(
                    bgcolor=colors.PRIMARY,
                    color=colors.ON_PRIMARY,
                )
        
        # 禁用其他控件
        controls = [
            self.prompt_textfield,
            self.content_type_dropdown,
            self.ai_provider_dropdown,
            self.ai_model_dropdown,
        ]
        
        for control in controls:
            if control:
                control.disabled = is_generating
        
        self.page.update()
    
    def _show_error(self, message: str) -> None:
        """显示错误消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.ERROR),
                bgcolor=colors.ERROR_CONTAINER,
                duration=4000,
            )
        )
    
    def _show_success(self, message: str) -> None:
        """显示成功消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.GREEN),
                bgcolor=colors.GREEN_CONTAINER,
                duration=3000,
            )
        )
    
    def _show_info(self, message: str) -> None:
        """显示信息消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message),
                duration=2000,
            )
        )
    
    # 预设提示词
    def get_preset_prompts(self) -> Dict[str, List[Dict[str, str]]]:
        """获取预设提示词"""
        return {
            "image": [
                {"name": "美丽风景", "prompt": "美丽的山川湖泊，日落时分，4K画质，超现实主义风格"},
                {"name": "未来城市", "prompt": "未来科技城市，霓虹灯光，赛博朋克风格，夜晚，高细节"},
                {"name": "可爱动物", "prompt": "可爱的小猫，毛茸茸的，大眼睛，温馨的光线，卡通风格"},
                {"name": "抽象艺术", "prompt": "抽象艺术作品，鲜艳的色彩，几何形状，现代艺术风格"},
            ],
            "video": [
                {"name": "自然风景", "prompt": "美丽的自然风景，四季变化，时间流逝，4K画质"},
                {"name": "城市生活", "prompt": "繁忙的城市生活，人群流动，交通，现代都市"},
                {"name": "科幻场景", "prompt": "未来科幻场景，太空飞船，星球，宇宙探索"},
            ],
            "audio": [
                {"name": "轻松音乐", "prompt": "轻松愉快的背景音乐，钢琴和吉他，适合工作学习"},
                {"name": "自然声音", "prompt": "大自然的声音，鸟鸣，流水声，森林环境音"},
                {"name": "电子音乐", "prompt": "现代电子音乐，节奏感强，适合运动和舞蹈"},
            ],
            "text": [
                {"name": "故事创作", "prompt": "创作一个关于勇气和友谊的短篇故事"},
                {"name": "诗歌创作", "prompt": "写一首关于春天的现代诗歌"},
                {"name": "商业文案", "prompt": "为一款新的智能手表写产品描述文案"},
            ],
        }
    
    async def refresh_content_list(self) -> None:
        """刷新内容列表"""
        try:
            # 从状态管理器获取最新内容
            content_list = await self.state_manager.get_content_list()
            
            # TODO: 更新界面显示
            logger.info(f"Content list refreshed: {len(content_list)} items")
            
        except Exception as e:
            logger.error(f"Failed to refresh content list: {e}")